Skip to content

Conversation

@Binary-Cat-01
Copy link

No description provided.

private String message;
private boolean isReceived = false;

public Message() {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

зачем явно прописывать конструктор по умолчанию?

wait();
} catch (InterruptedException e) {
Thread.currentThread()
.interrupt();
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

зачем?

isReceived = true;

notifyAll();
}
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Размещать функциональность отправки и получения сообщения в самом Message - грубая ошибка. Завтра я захочу логику отправки-получения переделать через брокер сообщений или еще как-то - почему я при этом должен менять саму сущность "сообщение"?

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

То есть текущий класс надо либо переименовать, либо выделить класс логики, который будет отвечать за обработку сообщения

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Но я бы просто вынес отправку и получение в логику отдельных сущностей - тогда любой потенциальный полиморфизм будет реализовать проще


public class MessageReceiver implements Runnable {
private final Message message;
private final Consumer<String> stringConsumer;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Интересная идея. Но не всегда корректная на практике. В данном случае класс, создающий сущность получателя (или отправителя), должен знать, что будет происходить при отправке или получении. Чаще всего это не будет его ответственностью

message.send(stringSupplier.get());
}
}
}
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вердикт: технические решения местами интересные, с зонами ответственности классов перемудрил

@Override
public void run() {
while (!Thread.currentThread()
.isInterrupted()) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

лишний перенос строки

;
} catch (InterruptedException e) {
Thread.currentThread()
.interrupt();
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

?


logger.log("Остаток товаров на складе - %d".formatted(depot.getStock()));
}
}
Copy link
Owner

@KFalcon2022 KFalcon2022 Oct 20, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Хорошая идея. Но Depot тут определенно лишний, из-за него слушатель получает сильно много ответственности. Как вариант - можно пост-эффект тоже передавать лямбдой, этой будет логичнее

Ну и с названием класса можно подумать, ибо сейчас оно не отражает суть. Но это не так страшно

if ("finish".equalsIgnoreCase(stringSupplier.get())) {
break;
}
;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

?

Thread.sleep(Duration.ofSeconds(1));

if ("finish".equalsIgnoreCase(stringSupplier.get())) {
break;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

прохладная история, если есть флаг остановки

int surplus = 0;

while (!Thread.currentThread()
.isInterrupted()) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

лишний перенос

surplus = intSupplier.getAsInt();
}

Thread.sleep(Duration.ofSeconds(random.nextInt(1, 4)));
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

не помню в условии требований к простою у покупателей или поставщиков

}

logger.log("Остаток товаров - %d. %s пытается купить %d товаров.".formatted(stock, Thread.currentThread()
.getName(), count));
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

лишний перенос

}
}

logger.log("Остаток товаров - %d. %s пытается купить %d товаров.".formatted(stock, Thread.currentThread()
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

не логичнее в методы логгера докрутить varargs и дать возможность передавать параметры для форматирования? Чтобы не форматировать вручную в бизнес-коде

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants